﻿using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Darius.API.Application.Commands.Import
{
    public class FileImportHandler : IRequestHandler<FileImportCommand, FileExportResult>
    {
        private readonly IBaseRepositorys<SaleOrders> salsorderrepository;

        public FileImportHandler(IBaseRepositorys<SaleOrders> salsorderrepository)
        {
            this.salsorderrepository = salsorderrepository;
        }

        public async Task<FileExportResult> Handle(FileImportCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportResult();
            var list= salsorderrepository.GetAll().ToList();
            Console.WriteLine(list.Count);
            var book=new XSSFWorkbook();
            var sheet=book.CreateSheet("销售订单表");
            //创建表头
            var row1=sheet.CreateRow(0);
            //写入表头
            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(1).SetCellValue("订单编号");
            row1.CreateCell(2).SetCellValue("备注");
            row1.CreateCell(3).SetCellValue("创建日期");
            row1.CreateCell(4).SetCellValue("创建人");
            //行数
            int i = 1;
            foreach (var item in list)
            {
                row1=sheet.CreateRow(i);
                row1.CreateCell(0).SetCellValue(i+1);
                row1.CreateCell(1).SetCellValue(item.OrderNo);
                row1.CreateCell(2).SetCellValue(item.OrderNotes);
                row1.CreateCell(3).SetCellValue(item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                row1.CreateCell(4).SetCellValue(item.CreateName);
                i++;
            }
            byte[] bytes;
            using(MemoryStream ms=new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }
            string contextType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string fileName = "订单列表.xlsx";
            result.FileBytes = bytes;
            result.MimeType = contextType;
            result.FileName = fileName;
            return result;
        }
    }
}
